package tecpizza;


import java.util.List;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import negocio.Cliente;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author tecnico
 */
public class TelaClientes extends javax.swing.JFrame {

    /**
     * Creates new form TelaClientes
     */
    public TelaClientes() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelTitulo = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabelnome = new javax.swing.JLabel();
        jLabeltelefone = new javax.swing.JLabel();
        jLabelendereco = new javax.swing.JLabel();
        jLabelnumero = new javax.swing.JLabel();
        jLabelbairro = new javax.swing.JLabel();
        jTextFieldnome = new javax.swing.JTextField();
        jTextFieldtelefone = new javax.swing.JTextField();
        try{
            jTextFieldtelefone = new JFormattedTextField(new MaskFormatter("####-####"));
        }catch (Exception e){

        }
        jTextFieldendereco = new javax.swing.JTextField();
        jTextFieldnumero = new javax.swing.JTextField();
        jTextFieldbairro = new javax.swing.JTextField();
        jButtonsalvar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablelista = new javax.swing.JTable();
        jLabelNomeLista = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldComplemento = new javax.swing.JTextField();
        jTextFieldCodigo = new javax.swing.JTextField();
        jButtonAlterar = new javax.swing.JButton();

        setTitle("TecPizzas - Cadastro de Clientes");
        setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabelTitulo.setText("Cadastrar Clientes");
        getContentPane().add(jLabelTitulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 22, 190, -1));

        jSeparator1.setMinimumSize(new java.awt.Dimension(50, 20));
        getContentPane().add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 42, 580, 10));

        jLabelnome.setText("Nome:");
        getContentPane().add(jLabelnome, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 73, 40, -1));

        jLabeltelefone.setText("Telefone:");
        getContentPane().add(jLabeltelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 99, 130, -1));

        jLabelendereco.setText("Endereço:");
        getContentPane().add(jLabelendereco, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 125, 100, -1));

        jLabelnumero.setText("Número:");
        getContentPane().add(jLabelnumero, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 151, 50, -1));

        jLabelbairro.setText("Bairro:");
        getContentPane().add(jLabelbairro, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 179, 40, -1));
        getContentPane().add(jTextFieldnome, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 70, 340, -1));
        getContentPane().add(jTextFieldtelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 96, 120, -1));
        getContentPane().add(jTextFieldendereco, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 122, 340, -1));
        getContentPane().add(jTextFieldnumero, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 148, 120, -1));
        getContentPane().add(jTextFieldbairro, new org.netbeans.lib.awtextra.AbsoluteConstraints(77, 175, 240, -1));

        jButtonsalvar.setText("Salvar");
        jButtonsalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonsalvarActionPerformed(evt);
            }
        });
        getContentPane().add(jButtonsalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 250, 116, -1));

        jTablelista.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jTablelista.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Código", "Nome", "Telefone", "Endereço", "Número", "Complemento", "Bairro", "Alterar", "Excluir"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTablelista.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jTablelista.setDragEnabled(true);
        jTablelista.setName("");
        jTablelista.getTableHeader().setReorderingAllowed(false);
        jTablelista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTablelistaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTablelista);
        jTablelista.getColumnModel().getColumn(0).setResizable(false);
        jTablelista.getColumnModel().getColumn(1).setResizable(false);
        jTablelista.getColumnModel().getColumn(2).setResizable(false);
        jTablelista.getColumnModel().getColumn(3).setResizable(false);
        jTablelista.getColumnModel().getColumn(4).setResizable(false);
        jTablelista.getColumnModel().getColumn(5).setResizable(false);
        jTablelista.getColumnModel().getColumn(6).setResizable(false);
        jTablelista.getColumnModel().getColumn(7).setResizable(false);
        jTablelista.getColumnModel().getColumn(8).setResizable(false);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 318, 580, 260));

        jLabelNomeLista.setText("                                                                        Lista de Clientes");
        jLabelNomeLista.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        getContentPane().add(jLabelNomeLista, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 294, 580, -1));

        jLabel1.setText("Complemento:");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, 90, -1));

        jTextFieldComplemento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldComplementoActionPerformed(evt);
            }
        });
        getContentPane().add(jTextFieldComplemento, new org.netbeans.lib.awtextra.AbsoluteConstraints(306, 148, 110, -1));
        getContentPane().add(jTextFieldCodigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 70, 110, -1));

        jButtonAlterar.setText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });
        getContentPane().add(jButtonAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 250, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

        
    private void jButtonsalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonsalvarActionPerformed
      
          
      
        
        if (jTextFieldnome.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite seu Nome !");
            return;
        }

        if (jTextFieldbairro.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o Bairro !");
            return;
        }

        if (jTextFieldendereco.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o Endereço !");
            return;
        }

        if (jTextFieldnumero.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o Número !");
            return;
        }

        if (jTextFieldtelefone.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite seu Telefone !");
        }
        
        

        Cliente cliente = new Cliente();
        cliente.setNome(jTextFieldnome.getText());
        cliente.setTelefone(jTextFieldtelefone.getText());
        cliente.setEndereco(jTextFieldendereco.getText());
        cliente.setNumero(jTextFieldnumero.getText());
        cliente.setBairro(jTextFieldbairro.getText());
        cliente.setComplemento(jTextFieldComplemento.getText());
        cliente.salvar();

        JOptionPane.showMessageDialog(null, "Cadastro Feito com Sucesso!");
        
        jTextFieldnome.setText("");
        jTextFieldendereco.setText("");
        jTextFieldnumero.setText("");
        jTextFieldtelefone.setText("");
        jTextFieldComplemento.setText("");
        jTextFieldbairro.setText("");
        
    }//GEN-LAST:event_jButtonsalvarActionPerformed

    private void jTextFieldComplementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldComplementoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldComplementoActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        jButtonsalvar.setVisible(true);
        jTextFieldCodigo.setVisible(false);
        jButtonAlterar.setVisible(false);
        atualizaTabela();
    }//GEN-LAST:event_formWindowActivated

    
    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        if(jTextFieldnome.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Erro ! O campo Nome não foi preenchido");
            return;
        }
        if(jTextFieldendereco.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Erro ! O campo Endereço não foi preenchido"); 
            return;
        }
        
        if(jTextFieldtelefone.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Erro ! O campo Telefone não foi preenchido");
            return;
        }
        if(jTextFieldnumero.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Erro ! O campo Número não foi preenchido"); 
            return;
        }
        
        if(jTextFieldbairro.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Erro ! O campo Bairro não foi preenchido"); 
            return;
        }
        
        
        Cliente cliente = new Cliente();
        
        cliente.setNome(jTextFieldnome.getText());
        cliente.setCodigo(Integer.parseInt(jTextFieldCodigo.getText()));
        cliente.setEndereco(jTextFieldendereco.getText());
        cliente.setNumero(jTextFieldnumero.getText());
        cliente.setTelefone(jTextFieldtelefone.getText());
        cliente.setComplemento(jTextFieldComplemento.getText());
        cliente.setBairro(jTextFieldbairro.getText());
        cliente.alterar();
        
        JOptionPane.showMessageDialog(null, "Cliente alterado com Sucesso!");
        
        jTextFieldnome.setText("");
        jTextFieldendereco.setText("");
        jTextFieldnumero.setText("");
        jTextFieldtelefone.setText("");
        jTextFieldComplemento.setText("");
        jTextFieldbairro.setText("");
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void jTablelistaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablelistaMouseClicked
        Cliente cliente = new Cliente();
        if (jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,7)==true){
            jTextFieldnome.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,1).toString());
            jTextFieldtelefone.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,2).toString());
            jTextFieldCodigo.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,0).toString());
            jTextFieldendereco.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,3).toString());
            jTextFieldnumero.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,4).toString());
            jTextFieldComplemento.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,5).toString());
            jTextFieldbairro.setText(jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,6).toString());
            jButtonAlterar.setVisible(true);
            jButtonsalvar.setVisible(false);
            
            jTablelista.getModel().setValueAt(false, jTablelista.getSelectedRow() ,7);
            
        }else if (jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,8)==true){
            if (JOptionPane.showConfirmDialog(null,"Deseja excluir o Cliente " + 
                    jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,1).toString() + " ?",
                    "Confirma Exclusão",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
              
                String t = jTablelista.getModel().getValueAt(jTablelista.getSelectedRow() ,0).toString();
                
                if (cliente.podeExcluir(Integer.parseInt(t))){
                   cliente.excluir(Integer.parseInt(t));
                    JOptionPane.showMessageDialog(null,"Registro excluído com sucesso.");
               }else{
                   JOptionPane.showMessageDialog(null,"Este registro não pode ser excluído pois já foi utilizado em pedidos.");
               }
            }
        }
    }//GEN-LAST:event_jTablelistaMouseClicked

     
    
    
     private void atualizaTabela(){
        DefaultTableModel tTabela = (DefaultTableModel) jTablelista.getModel();
        tTabela.setNumRows(0);
        Cliente client = new Cliente();

        List<Cliente> cliente = client.getAll();
        if (cliente != null) {
            for (int linha = 0; linha < cliente.size(); linha++) {
                Cliente clientes = cliente.get(linha);

                tTabela.addRow(new Object[]{1});

                jTablelista.setValueAt(clientes.getCodigo(), linha, 0);
                jTablelista.setValueAt(clientes.getNome(), linha, 1);
                jTablelista.setValueAt(clientes.getTelefone(), linha, 2);
                jTablelista.setValueAt(clientes.getEndereco(), linha, 3);
                jTablelista.setValueAt(clientes.getNumero(), linha, 4);
                jTablelista.setValueAt(clientes.getComplemento(), linha, 5);
                jTablelista.setValueAt(clientes.getBairro(), linha, 6);
               


            }
        }
        
     }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaClientes().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonsalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelNomeLista;
    private javax.swing.JLabel jLabelTitulo;
    private javax.swing.JLabel jLabelbairro;
    private javax.swing.JLabel jLabelendereco;
    private javax.swing.JLabel jLabelnome;
    private javax.swing.JLabel jLabelnumero;
    private javax.swing.JLabel jLabeltelefone;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTablelista;
    private javax.swing.JTextField jTextFieldCodigo;
    private javax.swing.JTextField jTextFieldComplemento;
    private javax.swing.JTextField jTextFieldbairro;
    private javax.swing.JTextField jTextFieldendereco;
    private javax.swing.JTextField jTextFieldnome;
    private javax.swing.JTextField jTextFieldnumero;
    private javax.swing.JTextField jTextFieldtelefone;
    // End of variables declaration//GEN-END:variables
}

